package com.zcy.gift.service.impl;

import com.zcy.gift.doc.GiftDoc;
import com.zcy.gift.es.HighlightResultMapper;
import com.zcy.gift.query.GiftQuery;
import com.zcy.gift.service.IGiftSearchService;
import com.zcy.gift.util.PageList;
import com.zcy.gift.util.SearchUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author lucker
 * @date 2024/2/18 0:43
 */
@Service
public class GiftSearchServiceImpl implements IGiftSearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private HighlightResultMapper highlightResultMapper;

    @Override
    public PageList<GiftDoc> search(GiftQuery query) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 分词查询 name, 类型名称, 品牌名称
        if(StringUtils.isNotBlank(query.getKeyword())){
            List<QueryBuilder> must = boolQuery.must();
            must.add(QueryBuilders.multiMatchQuery(query.getKeyword(),"name", "tenantName", "typeName", "branName"));
        }
        // 这是添加查询条件
        queryBuilder.withQuery(boolQuery);

        // 排序 上架时间, 评论数排序, 价格, 销量
        String sortField = query.getSortField();
        if(StringUtils.isBlank(sortField)){
            sortField = "onsaletime";
        }
        String sortType = query.getSortType();

        // 设置一个默认排序,是升序
        SortOrder sortOrder = SortOrder.ASC;
        if("desc".equals(sortType)){
            sortOrder = SortOrder.DESC;
        }
        FieldSortBuilder sortBuilder = SortBuilders.fieldSort(sortField).order(sortOrder);
        queryBuilder.withSort(sortBuilder);
        // 分页查询
        // es的分页语法里面,from的值是从哪一条开始 计算公式: (当前页-1)*每页显示条数
        // 现在这个地方的分页参数里面,第一个参数是  (当前页-1)
        queryBuilder.withPageable(PageRequest.of(query.getPage() - 1, query.getRows()));

        // 4 高亮查询
        HighlightBuilder.Field nameField = new HighlightBuilder.Field("name")
                .preTags("<span style='color:red;font-weight:bold;'>").postTags("</span>");
        HighlightBuilder.Field tenantNameField = new HighlightBuilder.Field("tenantName")
                .preTags("<span style='color:red;font-weight:bold;'>").postTags("</span>");
        HighlightBuilder.Field typeNameField = new HighlightBuilder.Field("typeName")
                .preTags("<span style='color:red;font-weight:bold;'>").postTags("</span>");
        HighlightBuilder.Field branNameField = new HighlightBuilder.Field("branName")
                .preTags("<span style='color:red;font-weight:bold;'>").postTags("</span>");
        queryBuilder.withHighlightFields(nameField, tenantNameField, typeNameField, branNameField);
        // 聚合查询
        // 5 聚合查询,根据类型、品牌和租户的ID和name进行分组.并给要分后的组返回给前端
        TermsAggregationBuilder typeAggs = AggregationBuilders.terms("typeIdGroup").field("typeId").order(BucketOrder.count(false))
                .subAggregation(
                        AggregationBuilders.terms("typeNameGroup").field("typeName.keyword").order(BucketOrder.count(false))
                );
        TermsAggregationBuilder brandAggs = AggregationBuilders.terms("brandIdGroup").field("brandId").order(BucketOrder.count(false))
                .subAggregation(
                        AggregationBuilders.terms("brandNameGroup").field("branName.keyword").order(BucketOrder.count(false))
                );
        TermsAggregationBuilder tenantAggs = AggregationBuilders.terms("tenantIdGroup").field("tenantId").order(BucketOrder.count(false))
                .subAggregation(
                        AggregationBuilders.terms("tenantNameGroup").field("tenantName.keyword").order(BucketOrder.count(false))
                );
        queryBuilder.addAggregation(typeAggs);
        queryBuilder.addAggregation(brandAggs);
        queryBuilder.addAggregation(tenantAggs);


        // 调用es的分页查询
        AggregatedPage<GiftDoc> docPage = elasticsearchTemplate.queryForPage(queryBuilder.build(), GiftDoc.class, highlightResultMapper);
        // 将es返回给我们的分页数据,封装成我们自己的分页对象返回给前端
        List<GiftDoc> content = docPage.getContent();
        return new PageList<>(docPage.getTotalElements(),content);
    }
}
